# encoding: utf-8

import redis
from flask import json
from flask_sqlalchemy import SQLAlchemy
import config
from gevent import socket as gsocket


class MySQLAlchemy(SQLAlchemy):
    def create_session(self, options):
        options['autoflush'] = False
        return super(MySQLAlchemy, self).create_session(options)


db = SQLAlchemy()
redis.connection.socket = gsocket
pool = redis.ConnectionPool(**config.redis_config)
r = redis.StrictRedis(connection_pool=pool)


def set_redis(key, value):
    return r.set(name=key, value=json.dumps(value), ex=config.redis_ex)


def get_redis(key):
    value = r.get(key)
    if value:
        return json.loads(value)
    else:
        return value
